package fr.sedoo.metadata.client.ui.widget.field.impl;

import java.util.ArrayList;

import com.google.gwt.user.client.ui.HorizontalPanel;

import fr.sedoo.commons.client.widget.map.impl.AreaSelectorWidget;
import fr.sedoo.commons.client.widget.map.impl.MultipleAreaSelectorWidget;
import fr.sedoo.commons.shared.domain.GeographicBoundingBoxDTO;
import fr.sedoo.metadata.client.ui.widget.field.api.IsDisplay;
import fr.sedoo.metadata.client.ui.widget.field.api.IsEditor;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.shared.domain.MetadataDTO;

public class MultipleGeographicalExtent extends HorizontalPanel implements IsDisplay, IsEditor {
	protected MultipleAreaSelectorWidget areaSelector;

	public MultipleGeographicalExtent() {
		this(AreaSelectorWidget.DEFAULT_MAP_LAYER);
	}

	public MultipleGeographicalExtent(String mapLayer) {
		super();
		setWidth(FieldConstant.HUNDRED_PERCENT);
		areaSelector = new MultipleAreaSelectorWidget(mapLayer);
		add(areaSelector);
	}

	@Override
	public void display(MetadataDTO metadata) {
		areaSelector.enableDisplayMode();
		areaSelector.reset();
		ArrayList<GeographicBoundingBoxDTO> boxes = metadata.getGeographicalLocationPart().getBoxes();
		if (!boxes.isEmpty()) {
			areaSelector.setGeographicBoundingBoxDTOList(boxes);
		} else {
			areaSelector.setGeographicBoundingBoxDTOList(new ArrayList<GeographicBoundingBoxDTO>());
		}
	}

	@Override
	public void reset() {
		areaSelector.reset();
	}

	@Override
	public void flush(MetadataDTO metadata) {
		metadata.getGeographicalLocationPart().setBoxes(areaSelector.getGeographicBoundingBoxDTOList());
	}

	@Override
	public void edit(MetadataDTO metadata) {
		areaSelector.reset();
		areaSelector.enableEditMode();
		ArrayList<GeographicBoundingBoxDTO> boxes = metadata.getGeographicalLocationPart().getBoxes();
		if (!boxes.isEmpty()) {
			areaSelector.setGeographicBoundingBoxDTOList(boxes);
		} else {
			areaSelector.setGeographicBoundingBoxDTOList(new ArrayList<GeographicBoundingBoxDTO>());
		}
	}

	public ArrayList<GeographicBoundingBoxDTO> getBoxes() {
		MetadataDTO metadata = new MetadataDTO();
		flush(metadata);
		return metadata.getGeographicalLocationPart().getBoxes();
	}

	public void setBoxes(ArrayList<GeographicBoundingBoxDTO> boxes) {
		MetadataDTO metadata = new MetadataDTO();
		if (boxes != null) {
			metadata.getGeographicalLocationPart().setBoxes(boxes);
		}
		edit(metadata);
	}
}
